package com.stlm2.controller.pay;

import com.stlm2.dems.entity.*;
import com.stlm2.dems.service.IntegralGoodsService;
import com.stlm2.dems.service.IntegralOrderService;
import com.stlm2.dems.service.PeriodsService;
import com.stlm2.dems.service.UserService;
import com.stlm2.dems.user.entity.Account;
import com.stlm2.dems.user.entity.AccountState;
import com.stlm2.dems.user.service.AccountService;
import com.stlm2.util.codecontent.CodeContent;
import com.sun.tools.javac.jvm.Code;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * Author：fuchunyu
 * Date：2017/12/20
 * Description：积分支付
 */
@Controller
@RequestMapping("/integral")
public class IntegralPayController {

    @Resource
    private UserService userService;
    @Resource
    private IntegralGoodsService integralGoodsService;
    @Resource
    private AccountService accountService;
    @Resource
    private IntegralOrderService integralOrderService;
    @Resource
    private PeriodsService periodsService;

    /**
     * @param payPassword  支付密码
     * @param token 用户标识
     * @param code 订单编号
     * @return 支付成功
     */
    @ResponseBody
    @RequestMapping(value = "/pay.json", produces = "application/json;charset=utf-8")
    public String pay(String companyCode,String payPassword,String token,String code){
        User user=userService.getByToken(token);
        if (user==null)
            return CodeContent.returnLogin();
        IntegralOrder integralOrder=integralOrderService.getByCode(code);
        if(integralOrder==null)
            return CodeContent.returnFailure("获取订单错误！");
        if(StringUtils.isEmpty(payPassword))
            return CodeContent.returnFailure("帐户支付密码不能为空！");
        Account account=accountService.getByUserId(user.getId());
        if (account == null)
            return CodeContent.returnFailure("账户信息为空！");
        if (StringUtils.isBlank(account.getPassword()))
            return CodeContent.returnFailure("未设置支付密码!");
        if (StringUtils.isBlank(payPassword))
            return CodeContent.returnFailure("帐户密码不能为空！");
        if(user.getId()-integralOrder.getUserId()!=0)
            return CodeContent.returnFailure("支付用户和订单用户不匹配！");

        if (AccountState.Locked.equals(account.getAccountState()))
            return CodeContent.returnFailure("帐号已锁定！");
        else {

            if (!payPassword.equals(account.getPassword()))
                return CodeContent.returnFailure("支付密码错误!");
        }
        BigDecimal jifen = account.getRemainJiFen();
        if(integralOrder.getPayIntegral().compareTo(jifen)==1){
            return CodeContent.returnFailure("积分余额不足!");
        }
        IntegralOrder tempOrder=null;
        try {
            tempOrder = integralOrderService.pay(account, integralOrder);
        }catch (Exception e){
            return CodeContent.returnFailure(e.getMessage());
        }

        if (tempOrder != null && OrderState.Payment.equals(tempOrder.getOrderState())) {
            if(tempOrder.getGoodsType().equals(GoodsType.IntegralPrize)){
                Periods periods=periodsService.findEntityById(tempOrder.getPeriodsId());
                periods.setNowNum(periods.getNowNum()+tempOrder.getNum());
                periods.setParticipant(periods.getParticipant()!=null&&periods.getParticipant()!=""?periods.getParticipant()+","+tempOrder.getUserId():tempOrder.getUserId().toString());
                if(periods.getNowNum()>=periods.getTotalNum()){
                    if(periods.getWinning()==null){
                        String partctipants[]=periods.getParticipant().split(",");
                        Random random = new Random();
                        int i=random.nextInt(partctipants.length);
                        String winning=partctipants[i];
                        periods.setWinning(Integer.parseInt(winning));
                    }
                    periods.setState(0);
                    periods.setEndTime(new Date());

                    IntegralOrder perizeIntegralOrder=new IntegralOrder();
                    perizeIntegralOrder.setPeriodsId(periods.getId());
                    perizeIntegralOrder.setGoodsType(GoodsType.IntegralPrize);
                    perizeIntegralOrder.setOrderState(OrderState.Payment);

                    List<IntegralOrder> perizeIntegralOrderList=integralOrderService.getList(-1,-1,perizeIntegralOrder);
                    Date openTime=new Date();
                    Boolean flag=true;
                    for(IntegralOrder integralOrders:perizeIntegralOrderList){
                        if(integralOrders.getUserId()!=periods.getWinning()){
                            integralOrders.setOpenTime(openTime);
                            integralOrders.setPrizeState(false);
                        }else {
                            if(flag){
                                integralOrders.setPrizeState(true);
                                integralOrders.setOpenTime(openTime);
                                flag=false;
                            }else {
                                integralOrders.setPrizeState(false);
                                integralOrders.setOpenTime(openTime);
                            }
                        }
                        integralOrderService.updateEntity(integralOrders);
                    }

                    IntegralGoods integralGoods=integralGoodsService.findEntityById(tempOrder.getGoodsId());
                    if(integralGoods.getState()==1){
                        Periods newPeriods=new Periods();
                        newPeriods.setCode(periods.getCode()+1);
                        newPeriods.setGoodsId(integralGoods.getId());
                        newPeriods.setCreateTime(new Date());
                        newPeriods.setNowNum(0);
                        newPeriods.setState(integralGoods.getState());
                        newPeriods.setTotalNum(integralGoods.getTotalIntegral().intValue());
                        newPeriods.setUnitIntegral(integralGoods.getUnitIntegral());
                        periodsService.addEntity(newPeriods);
                    }
                }
                periodsService.updateEntity(periods);
            }
            return CodeContent.returnSuccess(null);
        } else {
            return CodeContent.returnFailure("支付失败!");
        }
    }
}
